package com.haier.unpackshell.loader;


import dalvik.system.DexClassLoader;

/**
 *  加载器
 */
public class ApkClassLoader extends DexClassLoader {

    private ClassLoader mGrandParent;
    private final String[] mInterfacePackageNames;

    public ApkClassLoader(String dexPath, String optimizedDirectory, String librarySearchPath,
                          ClassLoader parent, String[] interfacePackageNames) {
        super(dexPath, optimizedDirectory, librarySearchPath, parent);

        mGrandParent = parent.getParent();
        this.mInterfacePackageNames = interfacePackageNames;
    }

    @Override
    protected Class<?> loadClass(String className, boolean resolve) throws ClassNotFoundException {

        String packageName;
        int dot = className.lastIndexOf('.');
        if (dot != -1) {
            packageName = className.substring(0, dot);
        } else {
            packageName = "";
        }

        boolean isInterface = false;
        for (String interfacePackageName : mInterfacePackageNames) {
            if (packageName.equals(interfacePackageName)) {
                isInterface = true;
                break;
            }
        }

        if (isInterface) return super.loadClass(className, resolve);

        Class<?> clazz = findLoadedClass(className);
        if (clazz != null) return clazz;

        try {
            clazz = findClass(className);
        } catch (ClassNotFoundException e) {

            try {
                clazz = mGrandParent.loadClass(className);
            } catch (ClassNotFoundException e1) {
                e1.printStackTrace();
            }
        }
        return clazz;
    }
}
